package com.ljc.controller;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ljc.common.lang.Result;
import com.ljc.config.RabbitConfig;
import com.ljc.entity.*;
import com.ljc.search.mq.PostMqIndexMessage;
import com.ljc.utils.ValidationUtil;
import com.ljc.vo.CommentVo;
import com.ljc.vo.PostVo;

import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@Controller
public class PostController extends BaseController {
    @GetMapping("/category/{id:\\d*}")//   \\d*指定数字类型
    public String category(@PathVariable("id") Long id) {
        int pn = ServletRequestUtils.getIntParameter(httpServletRequest, "pn", 1);
        httpServletRequest.setAttribute("currentCategoryId", id);
        httpServletRequest.setAttribute("pn", pn);
        IPage created =
                postService.paging(getPage(), id, null, null, null, "created");
        httpServletRequest.setAttribute("pageData", created);
        return "post/category";
    }

    @GetMapping("/post/{id:\\d*}")//   \\d*指定数字类型
    public String detail(@PathVariable("id") Long id) {
        PostVo vo = postService.selectOnePost(new QueryWrapper<Post>().eq("p.id", id));
        Assert.notNull(vo, "文章已经被删除");

        postService.putViewCount(vo);
        //评论
        // 1分页,2文章id,3用户id,排xu
        IPage<CommentVo> results = commentService.paging(getPage(), vo.getId(), null, "created");
        httpServletRequest.setAttribute("currentCategoryId", vo.getCategoryId());
        httpServletRequest.setAttribute("post", vo);
        httpServletRequest.setAttribute("pageData", results);
        return "post/detail";
    }

    /**
     * 判断用户是否收藏了文章
     *
     * @param pid
     * @return
     */
    @ResponseBody
    @PostMapping("/collection/find/")
    public Result collectionFind(Long pid) {
        int count = collectionService.count(new QueryWrapper<UserCollection>()
                .eq("user_id", getProfileId())
                .eq("post_id", pid));
        return Result.success(MapUtil.of("collection", count > 0));
    }

    @ResponseBody
    @PostMapping("/collection/add/")
    public Result collectionAdd(Long pid) {
        Post post = postService.getById(pid);
        Assert.isTrue(post != null, "该帖子已经被删除");
        int count = collectionService.count(new QueryWrapper<UserCollection>()
                .eq("user_id", getProfileId())
                .eq("post_id", pid));
        if (count > 0) {
            return Result.fail("你已经收藏了!");
        }
        UserCollection collection = new UserCollection();
        collection.setUserId(getProfileId());
        collection.setPostId(pid);
        collection.setCreated(new Date());
        collection.setModified(new Date());
        collection.setPostUserId(post.getUserId());
        collectionService.save(collection);
        return Result.success();
    }

    @ResponseBody
    @PostMapping("/collection/remove/")
    public Result collectionRemove(Long pid) {
        Post post = postService.getById(pid);
        Assert.isTrue(post != null, "该帖子已经被删除");

        collectionService.remove(new QueryWrapper<UserCollection>()
                .eq("user_id", getProfileId())
                .eq("post_id", pid));
        return Result.success();
    }

    @GetMapping("/post/edit")
    public String edit() {
        String id = httpServletRequest.getParameter("id");
        if (!StringUtils.isEmpty(id)) {
            Post post = postService.getById(id);
            Assert.isTrue(post != null, "该帖子已经被删除");
            Assert.isTrue(post.getUserId().longValue() == getProfileId(), "没有权限修改此文章!");
            httpServletRequest.setAttribute("post", post);
        }
        httpServletRequest.setAttribute("categories", categoryService.list());
        return "/post/edit";
    }

    @ResponseBody
    @PostMapping("/post/submit")
    public Result submit(Post post) {
        ValidationUtil.ValidResult validResult = ValidationUtil.validateBean(post);
        if (validResult.hasErrors()) {
            return Result.fail(validResult.getErrors());
        }
        if (post.getId() == null) {
            post.setUserId(getProfileId());

            post.setModified(new Date());
            post.setCreated(new Date());
            post.setCommentCount(0);
            post.setEditMode(null);
            post.setLevel(0);
            post.setRecommend(false);
            post.setViewCount(0);
            post.setVoteDown(0);
            post.setVoteUp(0);
            postService.save(post);

        } else {
            Post tempPost = postService.getById(post.getId());
            Assert.isTrue(tempPost.getUserId().longValue() == getProfileId().longValue(), "无权限编辑此文章！");

            tempPost.setTitle(post.getTitle());
            tempPost.setContent(post.getContent());
            tempPost.setCategoryId(post.getCategoryId());
            postService.updateById(tempPost);
        }
        //通知消息给mq,告诉更新或者添加
        amqpTemplate.convertAndSend(
                RabbitConfig.es_exchange,
                RabbitConfig.es_bind_key,
                new PostMqIndexMessage(post.getId(), PostMqIndexMessage.CREATE_OR_UPDATE));
        return Result.success().action("/post/" + post.getId());
    }

    @ResponseBody
    @Transactional
    @PostMapping("/post/delete")
    public Result deletePost(Long id) {
        Post post = postService.getById(id);
        Assert.notNull(post, "该帖子已经被删除!");
        Assert.isTrue(post.getUserId().longValue() == getProfileId().longValue(),
                "没有权限删除此文章!");
        postService.removeById(id);
        //删除相关信息收藏
        userMessageService.removeByMap(MapUtil.of("post_id", id));
        collectionService.removeByMap(MapUtil.of("post_id", id));

        //通知消息给mq,告诉删除
        amqpTemplate.convertAndSend(
                RabbitConfig.es_exchange,
                RabbitConfig.es_bind_key,
                new PostMqIndexMessage(post.getId(), PostMqIndexMessage.REMOVE));
        return Result.success().action("/user/index");

    }

    @ResponseBody
    @Transactional
//    添加事务后会导致commentService.saveOrUpdate(comment)不立即提交 导致未读消息查询不出当前的消息,影响即时通讯
    @PostMapping("/post/reply")
    public Result postReply(Long jid, String content) {
        Assert.notNull(jid, "找不到对应文章");
        Assert.hasLength(content, "评论内容不能为空");

        Post post = postService.getById(jid);
        Assert.isTrue(post != null, "该文章已被删除");

        Comment comment = new Comment();
        comment.setPostId(jid);
        comment.setContent(content);
        comment.setUserId(getProfileId());
        comment.setCreated(new Date());
        comment.setModified(new Date());
        comment.setLevel(0);
        comment.setVoteDown(0);
        comment.setVoteUp(0);
        commentService.saveOrUpdate(comment);

        //评论数量加一
        post.setCommentCount(post.getCommentCount() + 1);
        postService.updateById(post);
        //本周热议数量加一
        postService.incrCommentCountAndUnionForWeekRank(post.getId(), true);

        //通知作者有人评论了你的文章
        //评论自己的不需要通知
        if (comment.getUserId() != post.getUserId()) {
            UserMessage userMessage = new UserMessage();
            userMessage.setPostId(jid);
            userMessage.setCommentId(comment.getId());
            userMessage.setFromUserId(getProfileId());
            userMessage.setToUserId(post.getUserId());
            userMessage.setType(1);
            userMessage.setContent(content);
            userMessage.setCreated(new Date());
            userMessage.setStatus(0);
            userMessageService.save(userMessage);
            //即时通知作者(websocket)
            wsService.sendMessCountToUser(userMessage.getToUserId());
        }
        //通知 被@的人有人回复了你的文章
        if (content.startsWith("@")) {
            String username = content.substring(1, content.indexOf(" "));
            User user = userService.getOne(new QueryWrapper<User>().eq("username", username));
            if (user != null) {
                UserMessage userMessage = new UserMessage();
                userMessage.setPostId(jid);
                userMessage.setCommentId(comment.getId());
                userMessage.setFromUserId(getProfileId());
                userMessage.setToUserId(user.getId());
                userMessage.setType(2);
                userMessage.setContent(content);
                userMessage.setCreated(new Date());
                userMessage.setStatus(0);
                userMessageService.save(userMessage);
            }
        }



        return Result.success().action("/post/" + post.getId());

    }

    @ResponseBody
    @Transactional
    @PostMapping("/post/jieda-delete/")
    public Result jiedaDelete(Long id) {


        Assert.notNull(id, "评论不能为空!");
        Comment comment = commentService.getById(id);

        Assert.notNull(comment, "找不到对应的评论");
        if (comment.getUserId().longValue() != getProfileId().longValue()) {
            return Result.fail("不是你发表的评论");
        }
        commentService.removeById(id);

        //评论数量减一
        Post post = postService.getById(comment.getPostId());
        post.setCommentCount(post.getCommentCount() - 1);
        postService.saveOrUpdate(post);

        //热评数量减一
        postService.incrCommentCountAndUnionForWeekRank(comment.getPostId(), false);



        return Result.success(null);


    }

}

